package com.xiuxia.bopicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiuxia.bopicturebackend.exception.BusinessException;
import com.xiuxia.bopicturebackend.exception.ErrorCode;
import com.xiuxia.bopicturebackend.exception.ThrowUtils;
import com.xiuxia.bopicturebackend.model.dto.space.SpaceAddRequestDTO;
import com.xiuxia.bopicturebackend.model.dto.space.SpaceQueryRequestDTO;
import com.xiuxia.bopicturebackend.model.entity.Space;
import com.xiuxia.bopicturebackend.model.entity.SpaceUser;
import com.xiuxia.bopicturebackend.model.entity.User;
import com.xiuxia.bopicturebackend.model.enums.SpaceLevelEnum;
import com.xiuxia.bopicturebackend.model.enums.SpaceRoleEnum;
import com.xiuxia.bopicturebackend.model.enums.SpaceTypeEnum;
import com.xiuxia.bopicturebackend.model.vo.space.SpaceVO;
import com.xiuxia.bopicturebackend.service.SpaceService;
import com.xiuxia.bopicturebackend.mapper.SpaceMapper;
import com.xiuxia.bopicturebackend.service.SpaceUserService;
import com.xiuxia.bopicturebackend.service.UserService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author 17732
 * @description 针对表【space(空间)】的数据库操作Service实现
 * @createDate 2025-06-21 14:20:18
 */
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
        implements SpaceService {
    @Resource
    private UserService userService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private SpaceUserService spaceUserService;
    Map<Long, Object> lockMap = new ConcurrentHashMap<>();

    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        Integer spaceType = space.getSpaceType();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        SpaceTypeEnum spaceTypeEnum = SpaceTypeEnum.getEnumByValue(spaceType);
        if (add) {
            ThrowUtils.throwIf(StrUtil.isBlank(spaceName), ErrorCode.PARAMS_ERROR, "空间名称不能为空");
            ThrowUtils.throwIf(spaceLevel == null, ErrorCode.PARAMS_ERROR, "空间等级不能为空");
            ThrowUtils.throwIf(spaceType == null, ErrorCode.PARAMS_ERROR, "空间类型不能为空");
        }
        // 不是增加就是修改数据
        ThrowUtils.throwIf(spaceLevel != null && spaceLevelEnum == null, ErrorCode.PARAMS_ERROR, "空间等级不存在");
        ThrowUtils.throwIf(StrUtil.isNotBlank(spaceName) && spaceName.length() > 30, ErrorCode.PARAMS_ERROR, "空间名称过长");
        ThrowUtils.throwIf(spaceType != null && spaceTypeEnum == null, ErrorCode.PARAMS_ERROR, "空间类型不存在");
    }

    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (spaceLevelEnum != null) {
            long maxSize = spaceLevelEnum.getMaxSize();
            if (space.getMaxSize() == null) {
                space.setMaxSize(maxSize);
            }
            long maxCount = spaceLevelEnum.getMaxCount();
            if (space.getMaxCount() == null) {
                space.setMaxCount(maxCount);
            }
        }
    }

    /**
     * 创建空间（使用本地锁）
     * @param spaceAddRequestDTO 创建空间请求参数
     * @param loginUser 登录用户
     * @return
     */
   /* @Override
    public Long addSpace(SpaceAddRequestDTO spaceAddRequestDTO, User loginUser) {
        Space space = new Space();
        BeanUtil.copyProperties(spaceAddRequestDTO, space);
        if (spaceAddRequestDTO.getSpaceLevel() == null) {
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (StrUtil.isBlank(spaceAddRequestDTO.getSpaceName())) {
            space.setSpaceName("默认空间");
        }
        this.fillSpaceBySpaceLevel(space);
        this.validSpace(space, true);
        Long userId = loginUser.getId();
        space.setUserId(userId);
        ThrowUtils.throwIf(SpaceLevelEnum.COMMON.getValue() != spaceAddRequestDTO.getSpaceLevel() && !userService.isAdmin(loginUser), ErrorCode.NO_AUTH_ERROR, "无权限创建指定级别的空间");
        //加锁
        Object lock = lockMap.computeIfAbsent(userId, k -> new Object());
        synchronized (lock) {
            try {
                Long spaceId = transactionTemplate.execute(status -> {
                    boolean exists = this.lambdaQuery().eq(Space::getUserId, userId).exists();
                    ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "用户已创建空间,每个用户只能创建一个空间");
                    boolean result = this.save(space);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
                    return space.getId();
                });
                return Optional.ofNullable(spaceId).orElse(-1L);
            } finally {
                lockMap.remove(userId);
            }
        }
    }*/

    /**
     * 创建空间（使用Redisson分布式锁）
     *
     * @param spaceAddRequestDTO 创建空间请求参数
     * @param loginUser          登录用户
     * @return
     */
    @Override
    public Long addSpace(SpaceAddRequestDTO spaceAddRequestDTO, User loginUser) {
        ThrowUtils.throwIf(spaceAddRequestDTO == null, ErrorCode.PARAMS_ERROR);
        if (spaceAddRequestDTO.getSpaceLevel() == null) {
            spaceAddRequestDTO.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (StrUtil.isBlank(spaceAddRequestDTO.getSpaceName())) {
            spaceAddRequestDTO.setSpaceName("默认空间");
        }
        if (spaceAddRequestDTO.getSpaceType() == null) {
            spaceAddRequestDTO.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        Space space = new Space();
        BeanUtil.copyProperties(spaceAddRequestDTO, space);
        this.fillSpaceBySpaceLevel(space);
        this.validSpace(space, true);
        Long userId = loginUser.getId();
        space.setUserId(userId);
        ThrowUtils.throwIf(SpaceLevelEnum.COMMON.getValue() != space.getSpaceLevel() && !userService.isAdmin(loginUser), ErrorCode.NO_AUTH_ERROR, "无权限创建指定级别的空间");
        //加锁
        String redissonKey = "space:redisson:key" + userId;
        RLock redissonLock = redissonClient.getLock(redissonKey);
        try {
            boolean tryLock = redissonLock.tryLock();
            ThrowUtils.throwIf(!tryLock, ErrorCode.OPERATION_ERROR, "获取分布式锁失败");
            Long spaceId = transactionTemplate.execute(status -> {
                boolean exists = this.lambdaQuery().eq(Space::getUserId, userId).eq(Space::getSpaceType, spaceAddRequestDTO.getSpaceType()).exists();
                ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "用户已创建空间,每个用户只能创建一个空间");
                boolean result = this.save(space);
                ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
                // 如果是创建团队空间，就关联创建空间用户成员
                if (SpaceTypeEnum.TEAM.getValue() == spaceAddRequestDTO.getSpaceType()) {
                    SpaceUser spaceUser = new SpaceUser();
                    spaceUser.setSpaceId(space.getId());
                    spaceUser.setUserId(userId);
                    spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                    result = spaceUserService.save(spaceUser);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建团队空间用户成员记录失败");
                }
                return space.getId();
            });
            return Optional.ofNullable(spaceId).orElse(-1L);
        } finally {
            if (redissonLock.isHeldByCurrentThread()) {
                redissonLock.unlock();
            }
        }
    }

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequestDTO spaceQueryRequestDTO) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequestDTO == null) {
            return queryWrapper;
        }
        Long id = spaceQueryRequestDTO.getId();
        Long userId = spaceQueryRequestDTO.getUserId();
        String spaceName = spaceQueryRequestDTO.getSpaceName();
        Integer spaceLevel = spaceQueryRequestDTO.getSpaceLevel();
        String sortField = spaceQueryRequestDTO.getSortField();
        String sortOrder = spaceQueryRequestDTO.getSortOrder();
        Integer spaceType = spaceQueryRequestDTO.getSpaceType();
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceType), "spaceType", spaceType);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        User user = userService.getById(space.getUserId());
        spaceVO.setUser(userService.getUserVO(user));
        return spaceVO;
    }

    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        // 对象列表 => 封装对象列表
        List<SpaceVO> spaceVOList = spaceList.stream().map(SpaceVO::objToVo).collect(Collectors.toList());
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    /**
     * 空间权限校验
     *
     * @param loginUser
     * @param space
     */
    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        // 仅本人或管理员可访问
        if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }

}




